package com.kkb.dynamiproxy;

import com.kkb.aop.AOP;
import com.kkb.aop.TranAOP;
import com.kkb.service.BookService;
import com.kkb.service.IService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyHandler implements InvocationHandler {
    private IService service;
    private AOP aop;


    public ProxyHandler(IService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            aop.before();
            Object invoke = method.invoke(service, args);//核心业务
            aop.after();
            return invoke;
        } catch (Exception e) {
            aop.exception();
            e.printStackTrace();
            throw e;
        } finally {
            aop.myFinally();
        }
    }

    public static void main(String[] args) {
        BookService bookService = new BookService();
        AOP tranAOP = new TranAOP();

        IService proxyService = (IService) Proxy.newProxyInstance(
          bookService.getClass().getClassLoader(),
          bookService.getClass().getInterfaces(),
          new ProxyHandler(bookService,tranAOP)
        );

        //代理对象干活
        proxyService.add();
        System.out.println(bookService.getClass());
        System.out.println(proxyService.getClass()+"-----------");
    }
}
